package com.hqyj.springboot.filter;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;

@WebFilter
public class ParamFilter implements Filter {
 private static final Logger LOGGER = LoggerFactory.getLogger(ParamFilter.class);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        LOGGER.debug("===Init Filter===");

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        LOGGER.debug("===Do Filter===");
        //将servletRequest转换为HttpServletRequest
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;

        // 因为HttpServletRequest 不能直接操作paramterMap，所有构建Wapper对象进行操作
        HttpServletRequestWrapper wrapper = new HttpServletRequestWrapper(req){
            // 重写wapper对象的getParameter方法，替换字符串
            @Override
           public String getParameter(String name){
               String value = super.getParameter(name);

               return StringUtils.isNotBlank(value) ?
                       value.replaceAll("fuck","***")
                       : "";
           }
           @Override
           public String[] getParameterValues(String name){
               String[] values = super.getParameterValues(name);
               if (values == null){
                   return new String[]{};
               }
               return Arrays.asList(values)
                       .stream()
                       .map(item -> item.replaceAll("fuck","***"))
                       .toArray(String[] :: new);
           }


        };



        // 将wapper和response对象交出去



        filterChain.doFilter(wrapper,servletResponse);
    }

    @Override
    public void destroy() {

        LOGGER.debug("===Destroy Filter===");
    }
}
